package com.moodswings;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.location.Location;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import java.net.URL;
import java.util.ArrayList;

/**
 * Main activity.
 */
public class MoodSwingsActivity extends Activity {

	protected PositionSense positionSense;
	public static final String PREF_NAME = "moodswingspref";

	/**
	 * Called when the activity is first created.
	 */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);


		positionSense = new PositionSense(this, null);

	}

	@Override
	protected void onResume() {
		super.onResume();
		positionSense.init();
	}

	@Override
	protected void onPause() {
		super.onPause();
		positionSense.close();
	}

	/**
	 * Menja pozadinu u skladu sa izborom raspolozenja.
	 */
	public void background(int a) {
		View view = findViewById(R.id.main);
		switch (a) {
			case 1:
				view.setBackgroundColor(0xEEFFFF00);
				break;
			case 2:
				view.setBackgroundColor(0xAA123456);
				break;
			case 3:
				view.setBackgroundColor(0xAAFFFFFF);
				break;
			case 4:
				view.setBackgroundColor(0xAAAABBAA);
				break;
			case 5:
				view.setBackgroundColor(0xAAFF0000);
				break;
			case 6:
				view.setBackgroundColor(0xAACCAAAA);
				break;
		}
	}

	public void clickHappy(View view) {
		Toast.makeText(this, R.string.happytoast, Toast.LENGTH_SHORT).show();
		background(1);
		collectInfo(1);
	}

	public void clickSad(View view) {
		Toast.makeText(this, R.string.sadtoast, Toast.LENGTH_SHORT).show();
		background(2);
		collectInfo(2);
	}


	public void clickLonely(View view) {
		Toast.makeText(this, R.string.lonelytoast, Toast.LENGTH_SHORT).show();
		background(3);
		collectInfo(3);

	}


	public void clickAngry(View view) {
		Toast.makeText(this, R.string.angrytoast, Toast.LENGTH_SHORT).show();
		background(4);
		collectInfo(4);


	}


	public void clickLove(View view) {
		Toast.makeText(this, R.string.lovetoast, Toast.LENGTH_SHORT).show();
		background(5);
		collectInfo(5);
	}


	public void clickContent(View view) {
		Toast.makeText(this, R.string.contenttoast, Toast.LENGTH_SHORT).show();
		background(6);
		collectInfo(6);
	}


	// ---------------------------------------------------------------- menu

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {                     //kreira meni za opcije i dodaje mu 2 stavke
		menu.add(Menu.NONE, Menu.FIRST, 1, R.string.options);           //podesavanja
		//.setIcon(R.drawable.menu_options);
		menu.add(Menu.NONE, Menu.FIRST + 1, 2, R.string.map);           // i mapu
		//.setIcon(R.drawable.menu_options);
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {               //menja ekran u odabranu stranicu
		if (item.getItemId() == Menu.FIRST) {
			Intent intent = new Intent(this, OptionsActivity.class);
			startActivity(intent);
			return true;
		}
		if (item.getItemId() == Menu.FIRST + 1) {
			Intent intent = new Intent(this, MoodMapActivity.class);
			startActivity(intent);
			return true;
		}
		return false;
	}

	/**
	 * prikuplja podatke o korisniku i salje na server
	 */
	public void collectInfo(int num) {
		String IP;
		String ID;


		SharedPreferences settings = getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
		IP = settings.getString("IP", "192.168.1.3:8080");
		ID = settings.getString("ID", "USER");

		Location loc;
		final double latitude;
		final double longitude;
		final Long time;
		final int moodId;
		moodId = num;                                        //raspolozenje
		final String userId;                                 //izabrano ime korisnika
		userId = ID;
		final String ip = "http://" + IP + "/mood";          //ip adresa na koju se salju podaci (server)
		loc = positionSense.getLocation();
		if (loc == null) {                                   //Ako je null, ne radi nista, ne salje podatke
			return;
		}
		latitude = loc.getLatitude();                       //pokupi Latitude, Longitude i Time telefona
		longitude = loc.getLongitude();
		time = loc.getTime();


		AsyncTask<URL, Void, Void> a = new AsyncTask<URL, Void, Void>() {
			protected Void doInBackground(URL... urls) {       //u pozadini komunicira sa serverom

				HttpClient httpclient = new DefaultHttpClient();
				HttpPost httppost = new HttpPost(ip);          //pravi HttpPost koji ce se izvrsavati
				ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();

				//Dodaje parametre koje je sakupio
				nameValuePairs.add(new BasicNameValuePair("longitude", String.valueOf(longitude)));
				nameValuePairs.add(new BasicNameValuePair("lat", String.valueOf(latitude)));
				nameValuePairs.add(new BasicNameValuePair("moodId", String.valueOf(moodId)));
				nameValuePairs.add(new BasicNameValuePair("userId", userId));
				nameValuePairs.add(new BasicNameValuePair("time", String.valueOf(time)));
				//zavrsio dodavanje parametara


				HttpResponse response;

				try {
					httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
					httpclient.execute(httppost);             //izvrsava HttpPost, salje podatke serveru

				} catch (Exception e) {
					Log.e("MSW", "e", e);
				}


				return null;
			}                                          // ne vraca nista, samo treba da posalje upit
		}.execute();

		Log.d("TAG", "Data sent!");
	}
}

